package com.zhs.gccs.activity.gccs;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.annimon.stream.Stream;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.util.KeyboardUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.shape.view.ShapeButton;
import com.hjq.shape.view.ShapeEditText;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.mapbox.geojson.Point;
import com.zhs.gccs.BuildConfig;
import com.zhs.gccs.R;
import com.zhs.gccs.adapter.ComplaintImageAdapter;
import com.zhs.gccs.adapter.ReportGridTitleAdapter;
import com.zhs.gccs.base.BaseActivity;
import com.zhs.gccs.dao.TaskGccsDataDao;
import com.zhs.gccs.dao.TaskGccsFileDao;
import com.zhs.gccs.event.EventAddGccs;
import com.zhs.gccs.http.Api;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.model.GccsDict;
import com.zhs.gccs.model.GccsOfProject;
import com.zhs.gccs.model.GccsTaskData;
import com.zhs.gccs.model.GccsTaskDeleteFile;
import com.zhs.gccs.model.GccsTaskFile;
import com.zhs.gccs.model.SensorData;
import com.zhs.gccs.model.TabNoIconEntity;
import com.zhs.gccs.model.WaterMaker;
import com.zhs.gccs.utils.DateUtils;
import com.zhs.gccs.utils.DialogUtils;
import com.zhs.gccs.utils.FileUtils;
import com.zhs.gccs.utils.GPSUtils;
import com.zhs.gccs.utils.OnNoDoubleClickListener;
import com.zhs.gccs.utils.SharedPrefHelper;
import com.zhs.gccs.utils.ToastUtils;
import com.zhs.gccs.utils.Utils;
import com.zhs.gccs.view.LocationAddress;
import com.zhs.gccs.vo.ApplyGccsTask;
import com.zhs.gccs.vo.BaseBean;
import com.zhs.gccs.vo.GccsDictListBean;
import com.zhs.gccs.vo.GccsStatistics;
import com.zhs.gccs.widget.LuckGlideEngine;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import okhttp3.RequestBody;

/**
 * Created by chengzf on 2024/7/20.
 */
public class GccsUserTaskDataFormActivity extends BaseActivity {
    @BindView(R.id.fame_bar)
    FrameLayout fame_bar;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.btn_next)
    ShapeButton btn_next;
    @BindView(R.id.tab_layout)
    CommonTabLayout tab_layout;
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.iv_location)
    View iv_location;
    @BindView(R.id.tab_recycle_view)
    RecyclerView tab_recycle_view;
    @BindView(R.id.image_recycle)
    RecyclerView image_recycle;
    @BindView(R.id.radio_1)
    RadioGroup radio_1;
    @BindView(R.id.radio_2)
    RadioGroup radio_2;
    @BindView(R.id.ed_remark)
    ShapeEditText ed_remark;

    // 图片列表
    ArrayList<GccsTaskFile> mImageList = new ArrayList<>();
    private ComplaintImageAdapter imageAdapter;
    private TaskGccsDataDao taskGccsDataDao;
    private TaskGccsFileDao taskGccsFileDao;

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private List<GccsDictListBean.GccsDictInfoBean> titleList = new ArrayList<>();
    private ReportGridTitleAdapter mGccsTypeAdapter;


    private ApplyGccsTask taskBean;
    private String path;
    GccsStatistics gccsStatistics;
    private int tabPosition = 0;
    private boolean userForceLocation = false;
    private LocationAddress locationAddress;
    private LocationClient mBaiduLocationClient;
    private SensorData sensorData;
    private SensorManager sensorManager;
    SensorEventListener sensorEventListener;

    AMapLocationClient mGaodeLocationClient;
    GccsTaskData gccsTaskData;


    public static void start(Context context,
                             ApplyGccsTask bean,
                             String path,
                             GccsStatistics gccsStatistics,GccsTaskData gccsTaskData) {
        Intent intent = new Intent(context, GccsUserTaskDataFormActivity.class);
        intent.putExtra("task", bean);
        intent.putExtra("path", path);
        intent.putExtra("gccsStatistics", gccsStatistics);
        intent.putExtra("gccsTaskData", gccsTaskData);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report_spot_check);
        ImmersionBar.with(this).transparentBar().statusBarDarkFont(true).init();
        ButterKnife.bind(this);
        fame_bar.setPadding(0, ImmersionBar.getStatusBarHeight(this), 0, 0);
        taskGccsFileDao = new TaskGccsFileDao();
        taskGccsDataDao = new TaskGccsDataDao();
        Intent intent = getIntent();
        taskBean = (ApplyGccsTask) intent.getSerializableExtra("task");
        gccsStatistics = (GccsStatistics) intent.getSerializableExtra("gccsStatistics");
        if(intent.hasExtra("path")){
            path = intent.getStringExtra("path");
        }
        if(intent.hasExtra("gccsTaskData")){
            gccsTaskData = (GccsTaskData) intent.getSerializableExtra("gccsTaskData");
        }
        mGccsTypeAdapter = new ReportGridTitleAdapter();
        tab_recycle_view.setLayoutManager(new GridLayoutManager(context, 3));
        tab_recycle_view.setAdapter(mGccsTypeAdapter);
        mGccsTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                for (int i1 = 0; i1 < mGccsTypeAdapter.getData().size(); i1++) {
                    GccsDictListBean.Children taskBean = mGccsTypeAdapter.getData().get(i1);
                    if (i == i1) {
                        taskBean.setCheck(!taskBean.isCheck());
                    } else {
                        taskBean.setCheck(false);
                    }
                }
                mGccsTypeAdapter.setNewData(mGccsTypeAdapter.getData());
            }
        });

        imageAdapter = new ComplaintImageAdapter();
        image_recycle.setLayoutManager(new GridLayoutManager(context, 3));
        image_recycle.setAdapter(imageAdapter);

        imageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if (imageAdapter.getData().get(i).isDefault()) {
                    XXPermissions.with(GccsUserTaskDataFormActivity.this).permission(
                            Manifest.permission.MANAGE_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA
                    ).request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(@NonNull List<String> list, boolean b) {
                            toTakePhoto();
                        }

                        @Override
                        public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {

                        }
                    });
                }else {
                    if(mImageList!=null&&mImageList!=null){
                        GccsTaskFile gccsTaskFile = imageAdapter.getData().get(i);
                        int currentTaskFile = 0 ;
                        ArrayList<LocalMedia> selectList = new ArrayList<>();
                        for (int index = 0; index < mImageList.size(); index++) {
                            GccsTaskFile imageBean = mImageList.get(index);
                            if(!imageBean.isDefault()){
                                if((!TextUtils.isEmpty(imageBean.getId())&&imageBean.getId().equals(gccsTaskFile.getId()))
                                        ||(!TextUtils.isEmpty(imageBean.getLocalId())&&imageBean.getLocalId().equals(gccsTaskFile.getLocalId()))){
                                    currentTaskFile = index ;
                                }
                                String url = imageBean.getLocalUrl();
                                if(TextUtils.isEmpty(imageBean.getLocalUrl())){
                                    url = BuildConfig.BASEURL+"gccsFile/preview/image/"+imageBean.getId()
                                            +"?token="+ SharedPrefHelper.getInstance().getToken();
                                }
                                LocalMedia media = new LocalMedia();
                                media.setPath(url);
                                media.setRealPath(url);
                                media.setCutPath(url);
                                media.setCompressPath(url);
                                media.setOriginalPath(url);
                                media.setPosition(i);
                                selectList.add(media);
                            }
                        }
                        PictureSelector.create(context)
                                .openPreview()
//                            .setImageEngine(GlideEngine.createGlideEngine())
                                .setImageEngine(LuckGlideEngine.createGlideEngine())
                                .startActivityPreview(currentTaskFile, false, selectList);
                    }
                }
            }
        });
        imageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if (view.getId() == R.id.delete_cover) {
                    DialogUtils.showPromote2(context, "确认删除该影像?", null, new DialogUtils.OnConfirmListener() {
                        @Override
                        public void onConfirmed() {
//                            GccsTaskFile remove = imageAdapter.getData().remove(i);
                            GccsTaskFile remove = mImageList.remove(i);
                            imageAdapter.setComplaintData(mImageList);
                            if(TextUtils.isEmpty(remove.getId())&&
                                    !TextUtils.isEmpty(remove.getLocalId())){
                                remove = taskGccsFileDao.findByFileLocalId(remove.getLocalId());
                            }
                            if(TextUtils.isEmpty(remove.getId())){
                                if(remove.getLocalId()!=null){
                                    taskGccsFileDao.deleteByLocalId(remove.getLocalId());
                                }
                            }else {
                                sendDeleteFileRequest(remove);
                            }
                        }
                    });
                }
            }
        });


        if (path != null) {
            GccsTaskFile gccsTaskFile = new GccsTaskFile();
//            mImageList.add(new CommplaintBean(path, "", false));
            gccsTaskFile.setLocalUrl(path);
            mImageList.add(gccsTaskFile);
        }
        if(gccsTaskData!=null){
//            List<GccsTaskFile> taskFiles = taskGccsFileDao.
//                    findByDataId(gccsTaskData.getId());//本地还没上传的
//            if(gccsTaskData.getFileList()==null||gccsTaskData.getFileList().size()==0){
//                gccsTaskData.setFileList(taskFiles);
//            }else if(taskFiles!=null&&taskFiles.size()>0){//本地有缓存都是离线文件
//                Stream.of(taskFiles).forEach(item->{
//                    gccsTaskData.getFileList().add(item);
//                });
//            }
        }
        if(gccsTaskData!=null&&gccsTaskData.getFileList()!=null){
            mImageList.addAll(gccsTaskData.getFileList());
        }
        imageAdapter.setComplaintData(mImageList);

        /*if (locationAddress!=null){
            tv_location.setText(locationAddress.getLon() +"°E" +"\n"+ locationAddress.getLat() +"°N");
        }*/
        iv_location.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                userForceLocation = true;
                if(mBaiduLocationClient!=null){
                    mBaiduLocationClient.requestLocation();
                }else{
                    initBaiduLocation();
                }
//                if(mGaodeLocationClient!=null){
//                    mGaodeLocationClient.startLocation();
//                }else{
//                    initGdLocation();
//                }
            }
        });
        tab_layout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                Log.e("CZF", position + "");
                tabPosition = position;
                mGccsTypeAdapter.setNewData(titleList.get(position).getChildren());
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        initView();
    }
    private void initView() {
        iv_back.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });

        btn_next.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                toSaveFormData();
            }
        });
        try {
            //定位初始化
            initBaiduLocation();
            //        initGdLocation();
            initSensor();
            if(gccsTaskData!=null){
                //编辑
                tv_location.setText(
                        NumberUtil.decimalFormat("#.######", Double.parseDouble(gccsTaskData.getLongitude())) + "°E"
                                + " " + NumberUtil.decimalFormat("#.######",
                                Double.parseDouble(gccsTaskData.getLatitude())) + "°N");
            }
            //getGccsTypesData();
            if (gccsStatistics != null && gccsStatistics.getXmGccs() != null) {
                List<GccsOfProject> xmGccs = gccsStatistics.getXmGccs();
                List<GccsDict> gccs = gccsStatistics.getGccs();
                Stream.of(xmGccs).forEach(gccsxm -> {
                    GccsDict gccsDict = Stream.of(gccs).
                            filter(i -> i.getDbid().equals(gccsxm.getDbid())).findFirstOrElse(null);
                    if (gccsDict != null) {
                        GccsDict pgccsDict = Stream.of(gccs).
                                filter(i -> i.getDbid().equals(gccsDict.getPxmcsid())).findFirstOrElse(null);
                        gccsxm.setTypeName(gccsDict.getMc2());
                        gccsxm.setpType(gccsDict.getPxmcsid());
                        gccsxm.setpTypeName(pgccsDict.getMc2());
                    }
                });

                Stream.of(xmGccs).filter(i -> !"84FC98D87113C32AE050007F0100549D".equals(i.getDbid())).
                        groupBy(GccsOfProject::getpType)
                        .forEach(item -> {
                            List<GccsOfProject> gccsOfProjects = item.getValue();
                            GccsDictListBean.GccsDictInfoBean infoBean = new GccsDictListBean.GccsDictInfoBean();
                            infoBean.setDbid(item.getKey());
                            infoBean.setMc(gccsOfProjects.get(0).getpTypeName());
                            List<GccsDictListBean.Children> children = new ArrayList<>();
                            Stream.of(gccsOfProjects).forEach(p -> {
                                GccsDictListBean.Children child = new GccsDictListBean.Children();
                                child.setDbid(p.getDbid());
                                child.setMc(p.getTypeName());
                                children.add(child);
                            });
                            infoBean.setChildren(children);
                            titleList.add(infoBean);
                        });
                for (int i = 0; i < titleList.size(); i++) {
                    mTabEntities.add(new TabNoIconEntity(titleList.get(i).getMc()));
                }
                tab_layout.setTabData(mTabEntities);
                if(gccsTaskData!=null&&!TextUtils.isEmpty(gccsTaskData.getGccsPType())
                        &&!TextUtils.isEmpty(gccsTaskData.getGccsType())){
                    boolean found = false;
                    for(int i=0;i<titleList.size();i++){
                        GccsDictListBean.GccsDictInfoBean tab = titleList.get(i);
                        if(tab.getDbid().equals(gccsTaskData.getGccsPType())){
                            List<GccsDictListBean.Children> children = tab.getChildren();
                            GccsDictListBean.Children gcss = Stream.of(children).filter(ch -> ch.getDbid().equals(gccsTaskData.getGccsType())).findFirstOrElse(null);
                            if(gcss!=null){
                                gcss.setCheck(true);
                            }
                            mGccsTypeAdapter.setNewData(children);
                            tab_layout.setCurrentTab(i);
                            tabPosition = i;
                            found = true;
                            break;
                        }
                    }
                    if(!found){
                        mGccsTypeAdapter.setNewData(titleList.get(0).getChildren());
                        tab_layout.setCurrentTab(0);
                        tabPosition = 0;
                    }
                }else {
                    mGccsTypeAdapter.setNewData(titleList.get(0).getChildren());
                    tab_layout.setCurrentTab(0);
                    tabPosition = 0;
                }
            }
            if(gccsTaskData!=null){
                if ("1".equals(gccsTaskData.getQualified())){
                    radio_1.check(R.id.radio_1_2);
                }else if ("0".equals(gccsTaskData.getQualified())){
                    radio_1.check(R.id.radio_1_1);
                }
                if ("1".equals(gccsTaskData.getProblem())){
                    radio_2.check(R.id.radio_2_2);
                }else if ("0".equals(gccsTaskData.getQualified())){
                    radio_2.check(R.id.radio_2_1);
                }
                ed_remark.setText(gccsTaskData.getRemarks());
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }


    private void toTakePhoto() {
        PictureSelector.create(GccsUserTaskDataFormActivity.this)
//                .openGallery(SelectMimeType.ofImage())
                .openCamera(SelectMimeType.ofImage())
//                .setImageEngine(LuckGlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        for (int i1 = 0; i1 < result.size(); i1++) {
                            String path = result.get(i1).getRealPath();
                            writeImageWaterMarker(path);
                            GccsTaskFile gccsTaskFile = new GccsTaskFile();
                            gccsTaskFile.setLocalUrl(path);
//                            mImageList.add(new CommplaintBean(path, "", false));
                            mImageList.add(gccsTaskFile);
                        }
                        imageAdapter.setComplaintData(mImageList);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }
    private void writeImageWaterMarker(String path) {
        try {
            File file = new File(path);
            FileInputStream fis = new FileInputStream(file);
            Bitmap bitmap = BitmapFactory.decodeStream(fis);
            List<WaterMaker> waterMakers = new ArrayList<>();
            DecimalFormat fmt = new DecimalFormat("##0.00000");
            String latlon = "";
            if(gccsTaskData!=null&&gccsTaskData.getLatitude()!=null
                    &&gccsTaskData.getLongitude()!=null){
                latlon = "N" + fmt.format(Double.parseDouble(gccsTaskData.getLatitude()))
                        + "E" + fmt.format(Double.parseDouble(gccsTaskData.getLongitude()));
            }else {
                latlon = "N" + fmt.format(locationAddress.getLon())
                        + "E" + fmt.format(locationAddress.getLat());
            }
            String date = DateUtils.getDateTime();
            waterMakers.add(new WaterMaker("时间：", date));
            waterMakers.add(new WaterMaker("地点：", latlon));//parentActivity.getAddress()));
            waterMakers.add(new WaterMaker("采集人：", SharedPrefHelper.getInstance().getUserAccount()));
            waterMakers.add(new WaterMaker("项目：", taskBean.getPid()));
//            Bitmap textBitmap = BitmapUtil.createWatermark(context, bitmap, waterMakers);
            Bitmap textBitmap = Utils.saveWaterMask(context, 3, bitmap, date,
                    latlon,
                    gccsTaskData!=null?gccsTaskData.getAddress():locationAddress.getAddress(),
                    taskBean.getPid(),
                    SharedPrefHelper.getInstance().getUserAccount());
            FileUtils.saveBitmap(textBitmap, file.getCanonicalPath());
            Utils.writeLatLonIntoJpeg(file.getCanonicalPath(),
                    gccsTaskData!=null&&gccsTaskData.getLatitude()!=null?Double.parseDouble(gccsTaskData.getLatitude()):locationAddress.getLat(),
                    gccsTaskData!=null&&gccsTaskData.getLongitude()!=null?Double.parseDouble(gccsTaskData.getLongitude()):locationAddress.getLon(),
                    date,
                    SharedPrefHelper.getInstance().getUserAccount(),
                    "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBaiduLocationClient != null) {
            mBaiduLocationClient.stop();
        }
        if (mGaodeLocationClient != null) {
            mGaodeLocationClient.stopLocation();
        }

        if (sensorManager != null && sensorEventListener != null) {
            sensorManager.unregisterListener(sensorEventListener);
        }
    }
    private void initGdLocation() {
        try {
            mGaodeLocationClient = new AMapLocationClient(context);
            //初始化定位参数
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mGaodeLocationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation amapLocation) {
                    if (amapLocation != null) {
                        if (amapLocation.getErrorCode() == 0) {
                            float speed = amapLocation.getSpeed();//速度  单位：米/秒
                            float bearing = amapLocation.getBearing();//获取方向角信息
                            int gpsAccuracyStatus = amapLocation.getGpsAccuracyStatus();//获取GPS当前状态，返回值可参考AMapLocation类提供的常量
                            //定位成功回调信息，设置相关消息
                            //                        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                            //                        amapLocation.getLatitude();//获取纬度
                            //                        amapLocation.getLongitude();//获取经度
                            //                        amapLocation.getAccuracy();//获取精度信息
                            double[] doubles2 = GPSUtils.gcj02towgs84(amapLocation.getLongitude(), amapLocation.getLatitude());
                            Point p = Point.fromLngLat(doubles2[0], doubles2[1]);
//                            LocationAddress location = new LocationAddress(doubles2[0], doubles2[1],
//                                    amapLocation.getProvince(), amapLocation.getCity(), amapLocation.getDistrict(),
//                                    amapLocation.getStreet(), amapLocation.getStreet());
                            locationAddress = new LocationAddress(doubles2[0], doubles2[1],
                                    amapLocation.getProvince(), amapLocation.getCity(), amapLocation.getDistrict(),
                                    amapLocation.getStreet(), amapLocation.getStreet());
                            locationAddress.setAddress(amapLocation.getAddress());
                            if (gccsTaskData==null&&locationAddress != null) {
                                tv_location.setText(
                                        NumberUtil.decimalFormat("#.######", locationAddress.getLon()) + "°E"
                                                + " " + NumberUtil.decimalFormat("#.######", locationAddress.getLat()) + "°N");
                            }
                        } else {
                            //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                            Log.e("AmapError", "location Error, ErrCode:"
                                    + amapLocation.getErrorCode() + ", errInfo:"
                                    + amapLocation.getErrorInfo());
                        }
                    }
                }
            });
            //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption.setInterval(2000);
            //设置定位模式为AMapLocationMode.Device_Sensors，仅设备模式。
//            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
            //设置定位参数
            mGaodeLocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            //启动定位
            mGaodeLocationClient.startLocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void initBaiduLocation() {
        try {
            //百度地图发布https://lbs.baidu.com/index.php?title=android-privacy
            LocationClient.setAgreePrivacy(true);
            mBaiduLocationClient = new LocationClient(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("gcj02"); // 设置坐标类型---mapbox
        option.setScanSpan(1000);
        option.setNeedDeviceDirect(true);
        option.setIsNeedAddress(true); // 可选，设置是否需要地址信息，默认不需要
        option.setIsNeedLocationDescribe(true); // 可选，设置是否需要地址描述
        option.setLocationNotify(false); // 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIgnoreKillProcess(true); // 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop
        option.setIsNeedLocationDescribe(true); // 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation
        option.setIsNeedLocationPoiList(true); // 可选，默认false，设置是否需要POI结果，可以在BDLocation
        option.SetIgnoreCacheException(false); // 可选，默认false，设置是否收集CRASH信息，默认收集
        option.setIsNeedAltitude(true); // 可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        //设置locationClientOption
        mBaiduLocationClient.setLocOption(option);
        mBaiduLocationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
//                LogUtils.e("bdLocation = " + bdLocation.toString());
                //mapView 销毁后不在处理新接收的位置
                if (bdLocation == null || TextUtils.isEmpty(bdLocation.getAddrStr())) {
                    if(gccsTaskData==null){
                        tv_location.setText("定位失败");
                    }
                    return;
                }
                //百度的坐标转为mabox的坐标
//                if (mapBoxViewListener != null) mapBoxViewListener.onZoomChange((int) zoom);
                //bdLocation.getAdCode() bdLocation.getDirection()  bdLocation.getAddress()   bdLocation.getCity()
                double[] doubles2 = GPSUtils.gcj02towgs84(bdLocation.getLongitude(), bdLocation.getLatitude());
                Point p = Point.fromLngLat(doubles2[0], doubles2[1]);
                locationAddress = new LocationAddress(doubles2[0], doubles2[1],
                        bdLocation.getProvince(), bdLocation.getCity(), bdLocation.getDistrict(),
                        bdLocation.getTown(), bdLocation.getStreet());
                locationAddress.setAddress(bdLocation.getAddrStr());
                if(userForceLocation){
                    userForceLocation = false;
                    ToastUtils.toast("您的位置已更新");
                }
                if (gccsTaskData==null&&locationAddress != null) {
                    tv_location.setText(
                            NumberUtil.decimalFormat("#.######", locationAddress.getLon()) + "°E"
                                    + " " + NumberUtil.decimalFormat("#.######", locationAddress.getLat()) + "°N");
                }
            }
        });
        //开启地图定位图层
        mBaiduLocationClient.start();
    }

    private int axis_x;
    private int axis_y;

    private void initSensor() {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display dis = wm.getDefaultDisplay();
        int rotation = dis.getRotation();

        axis_x = SensorManager.AXIS_X;
        axis_y = SensorManager.AXIS_Y;
        switch (rotation) {
            case Surface.ROTATION_0:
                break;
            case Surface.ROTATION_90:
                axis_x = SensorManager.AXIS_Y;
                axis_y = SensorManager.AXIS_MINUS_X;
                break;
            case Surface.ROTATION_180:
                axis_x = SensorManager.AXIS_X;
                axis_y = SensorManager.AXIS_MINUS_Y;
                break;
            case Surface.ROTATION_270:
                axis_x = SensorManager.AXIS_MINUS_Y;
                axis_y = SensorManager.AXIS_X;
                break;
            default:
                break;
        }
//        Vibrator mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        // 实例化传感器管理者
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        // 初始化加速度传感器
        Sensor mAccelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//        Sensor.TYPE_ACCELEROMETER：加速度传感器
//        Sensor.TYPE_GYROSCOPE：陀螺仪传感器
//        Sensor.TYPE_LIGHT：光传感器
//        Sensor.TYPE_PROXIMITY：距离传感器
//        Sensor.TYPE_MAGNETIC_FIELD：磁力计传感器
        // 初始化地磁场传感器
        Sensor mMagneticFieldSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

        Sensor mSensorOrientation = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        SensorEventListener sensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                float azimuth = event.values[0];//SensorManager.DATA_X
                String direction = getDirection(-azimuth);
//                azimuth = (azimuth + 360) % 360;
                sensorData = new SensorData((int) azimuth, direction, azimuth + "");
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        };
        sensorManager.registerListener(sensorEventListener, mSensorOrientation, SensorManager.SENSOR_DELAY_GAME);
    }

    private String[] directions = {"北", "西北", "西", "西南", "南", "东南", "东", "东北"};

    private String getDirection(float azimuth) {
        azimuth = (azimuth + 360) % 360;
        int index = Math.round(azimuth / 45f) % 8;
        return directions[index];
    }

    private void getGccsTypesData() {
        toSubscribeSingleOb(Api.getDefault().gccsDictList(),
                new ProgressObserver(this, false) {
                    @Override
                    protected void _onNext(String result) {
                        GccsDictListBean bean = new Gson().fromJson(result, GccsDictListBean.class);//GsonImpl.get().toObject(result, SmTaskBean.class);
                        if (bean != null && bean.getCode() == 200 && bean.getData() != null && bean.getData().size() > 0) {
                            titleList.addAll(bean.getData());
                            for (int i = 0; i < titleList.size(); i++) {
                                mTabEntities.add(new TabNoIconEntity(titleList.get(i).getMc()));
                            }
                            tab_layout.setTabData(mTabEntities);
                            mGccsTypeAdapter.setNewData(titleList.get(0).getChildren());
                        } else {

                        }
                    }

                    @Override
                    protected void _onError(String result) {
                    }
                });
    }

    private void sendDeleteFileRequest(GccsTaskFile taskFile) {
        Map hashMap = new HashMap<>();
        hashMap.put("id", taskFile.getId());
        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault().
                        deleteGccsformFile(requestBody),
                new ProgressObserver(GccsUserTaskDataFormActivity.this, false) {
                    @Override
                    protected void _onNext(String result) {
                        Type type = TypeToken.getParameterized(BaseBean.class, GccsTaskDeleteFile.class).getType();
                        BaseBean<GccsTaskDeleteFile> bean = new Gson().fromJson(result, type);
                        if (bean != null && bean.getCode() == 200) {
                            ToastUtils.toast("删除成功");
                            taskGccsFileDao.deleteById(taskFile.getId());
                        } else {
                            ToastUtils.toast("删除失败");
                        }
                    }

                    @Override
                    protected void _onError(String result) {
                        ToastUtils.toast("提交失败");
                    }
                });
    }


    private void toSaveFormData() {
        KeyboardUtils.hideSoftInput(this);
        if(gccsTaskData==null&&locationAddress==null){
            ToastUtils.toast("定位失败");
            return;
        }
        GccsDictListBean.Children children = null;
        for (int i = 0; i < mGccsTypeAdapter.getData().size(); i++) {
            if (mGccsTypeAdapter.getData().get(i).isCheck()) {
                children = mGccsTypeAdapter.getData().get(i);
                break;
            }
        }

//        if (children == null) {
//            ToastUtils.toast("请选择工程措施类型");
//            return;
//        }

        String qualified = "";
        if (radio_1.getCheckedRadioButtonId() == R.id.radio_1_1) {
            // 不合格
            qualified = "0";
        } else if (radio_1.getCheckedRadioButtonId() == R.id.radio_1_2){
            // 合格
            qualified = "1";
        }

        String problem = "";
        if (radio_2.getCheckedRadioButtonId() == R.id.radio_2_1) {
            // 可立行立改
            problem = "0";
        } else if (radio_2.getCheckedRadioButtonId() == R.id.radio_2_2){
            // 需长期修改
            problem = "1";
        }
        String remark = ed_remark.getText().toString().trim();
        Map hashMap = new HashMap<>();
        if(gccsTaskData!=null){
            hashMap.put("id", gccsTaskData.getId());
            hashMap.put("latitude", gccsTaskData.getLatitude());
            hashMap.put("longitude", gccsTaskData.getLongitude());
            hashMap.put("address", gccsTaskData.getAddress());
        }else {
            hashMap.put("latitude", locationAddress == null ? "" : locationAddress.getLat());
            hashMap.put("longitude", locationAddress == null ? "" : locationAddress.getLon());
            hashMap.put("address", locationAddress == null ? "" : locationAddress.getAddress());
        }
        hashMap.put("taskId", taskBean.getId());
        hashMap.put("pid", taskBean.getPid());
        hashMap.put("gccsPType", titleList.get(tabPosition).getDbid());//该值
        hashMap.put("gccsType", children!=null?children.getDbid():null);
        hashMap.put("qualified", qualified);//是否合格
        hashMap.put("problem", problem);//
        hashMap.put("remarks", remark);
        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault().
                        saveGccsform(requestBody),
                new ProgressObserver(GccsUserTaskDataFormActivity.this, false) {
                    @Override
                    protected void _onNext(String result) {
                        Type type = TypeToken.getParameterized(BaseBean.class, GccsTaskData.class).getType();
                        BaseBean<GccsTaskData> bean = new Gson().fromJson(result, type);
                        if (bean != null && bean.getCode() == 200) {
                            ToastUtils.toast("提交成功");
                            //保存数据，并把文件保存本地，静默上传
                            saveGccsFileToLocal(bean.getData());
                            taskGccsDataDao.addOrUpdate(bean.getData());
//                                    ApplyGccsTaskActivity.start(ReportSpotCheckActivity.this);
                            //地图更新数据
                            EventBus.getDefault().post(new EventAddGccs());
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            ToastUtils.toast("提交失败");
                        }
                    }

                    @Override
                    protected void _onError(String result) {
                        ToastUtils.toast("提交失败");
                    }
                });
    }


    private void saveGccsFileToLocal(GccsTaskData data) {
        List<GccsTaskFile> files = imageAdapter.getData();
        if (files == null || files.size() == 0) return;
        Stream.of(files).forEach(file -> {
            if (!file.isDefault()&&TextUtils.isEmpty(file.getId())
                    &&TextUtils.isEmpty(file.getLocalId())) {//本地文件
                file.setSync(false);
                file.setFileType("0");//照片
                file.setPid(data.getPid());
                file.setTaskId(data.getTaskId());
                file.setDataId(data.getId());
                file.setGccsPType(data.getGccsPType());
                file.setGccsType(data.getGccsType());
                file.setLocalId(IdUtil.fastUUID());
                file.setDeleted(false);
                file.setAngle(sensorData.getAngle() + "");
                file.setAngleDeg(sensorData.getSensorAngle());
                file.setDegree(sensorData.getSensorDegree());
                if(gccsTaskData!=null){
                    file.setLat(gccsTaskData.getLatitude() + "");
                    file.setLon(gccsTaskData.getLongitude() + "");
                    file.setAddress(gccsTaskData.getAddress());
                }else {
                    file.setLat(locationAddress.getLat() + "");
                    file.setLon(locationAddress.getLon() + "");
                    file.setAddress(locationAddress.getAddress());
                }
                taskGccsFileDao.addOrUpdate(file);
            }
        });
    }
}
